#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/7/1 16:02
# @Author  : LiShan
# @Email   : lishan_1997@126.com
# @File    : counter.py
# @Note    : this is note
import cv2


def get_contours(img):
    """获取连通域

    :param img: 输入图片
    :return: 最大连通域
    """
    # 灰度化, 二值化, 连通域分析
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    ret, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)

    contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

    return contours[0]


def main():

    # 1.导入图片
    img = []

    img_cs1 = cv2.imread("./counter/cs1.jpg")
    img.append(img_cs1)
    img_cs2 = cv2.imread("./counter/cs2.jpg")
    img.append(img_cs2)
    img_cs3 = cv2.imread("./counter/cs3.jpg")
    img.append(img_cs3)

    # 2.获取连通域
    counter = []

    contour_cs1 = get_contours(img_cs1)
    counter.append(contour_cs1)
    print(len(contour_cs1))
    cv2.drawContours(img_cs1, contour_cs1, -1, (0, 0, 255), 2)
    # cv2.imshow("img_cs1", img_cs1)

    contour_cs2 = get_contours(img_cs2)
    counter.append(contour_cs2)
    print(len(contour_cs2))
    cv2.drawContours(img_cs2, contour_cs2, -1, (0, 0, 255), 2)
    # cv2.imshow("img_cs2", img_cs2)

    contour_cs3 = get_contours(img_cs3)
    counter.append(contour_cs3)
    print(len(contour_cs3))
    cv2.drawContours(img_cs3, contour_cs3, -1, (0, 0, 255), 2)
    # cv2.imshow("img_cs3", img_cs3)

    # 3.
    for i in range(len(counter)):
        ret = cv2.matchShapes(contour_cs1, counter[i], 1, 0)
        if ret < 0.1 and ret != 0:
            cv2.drawContours(img[i], contour_cs1, -1, (0, 0, 255), 2)
            cv2.imshow("match", img[i])
    ret0 = cv2.matchShapes(contour_cs1, contour_cs1, 1, 0)
    ret1 = cv2.matchShapes(contour_cs1, contour_cs2, 1, 0)
    ret2 = cv2.matchShapes(contour_cs1, contour_cs3, 1, 0)

    # 4.打印匹配度与显示结果
    print("相同的图像的 matchshapes:", ret0)
    print("相似的图像的 matchshapes:", ret1)
    print("不同的图像的 matchshapes:", ret2)

    # cv2.imshow("img_cs1", img_cs1)
    # cv2.imshow("img_cs2", img_cs2)
    # cv2.imshow("img_cc", img_cc)

    cv2.waitKey()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    main()

